package org.wu.framework.easy.markdown.utils;

import org.wu.framework.core.NormalUsedString;
import org.wu.framework.easy.markdown.endpoint.MarkDownTable;
import org.wu.framework.easy.markdown.endpoint.MarkDownTableData;
import org.wu.framework.easy.markdown.endpoint.MarkDownTableRow;

import java.nio.charset.StandardCharsets;

/**
 * markdown 工具
 */
public class MarkdownUtil {

    /**
     * 将markdown 转换成字符串数据
     *
     * @param markDownTable markdown
     * @return String
     */
    public static String markdownTableToString(MarkDownTable markDownTable) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<table>");
        stringBuilder.append(NormalUsedString.NEWLINE);
        for (MarkDownTableRow markDownTableRow : markDownTable.getMarkDownTableRowList()) {
            stringBuilder.append(NormalUsedString.SPACE).append("<tr>");
            stringBuilder.append(NormalUsedString.NEWLINE);
            for (MarkDownTableData markDownTableData : markDownTableRow.getMarkDownTableDataList()) {
                String value = markDownTableData.getValue();
                int colspan = markDownTableData.getColspan();
                int rowspan = markDownTableData.getRowspan();
                stringBuilder.append(NormalUsedString.SPACE).append(NormalUsedString.SPACE).append("<td");
                stringBuilder.append(" colspan= \"").append(colspan).append("\"");
                stringBuilder.append(" rowspan= \"").append(rowspan).append("\"");
                stringBuilder.append(">");
                stringBuilder.append(value);
                stringBuilder.append("</td>");
                stringBuilder.append(NormalUsedString.NEWLINE);
            }
            stringBuilder.append(NormalUsedString.SPACE).append("</tr>");
            stringBuilder.append(NormalUsedString.NEWLINE);
        }
        stringBuilder.append("</table>");
        stringBuilder.append(NormalUsedString.NEWLINE);
        return stringBuilder.toString();
    }

    /**
     * 将markdown 转换成字符串二进制
     *
     * @param markDownTable markdown
     * @return byte[]
     */
    public static byte[] markdownTableToByte(MarkDownTable markDownTable) {
        return markdownTableToString(markDownTable).getBytes(StandardCharsets.UTF_8);
    }
}
